using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Net8.Identity.Server.Services;
using OpenIddict.Abstractions;

namespace Net8.Identity.Server.Pages
{
    /// <summary>
    /// 授权页
    /// </summary>
    [Authorize]
    public class ConsentModel : PageModel
    {
        private readonly ILogger<ConsentModel> _logger;
        private readonly IOpenIddictApplicationManager _applicationManager;
        public ConsentModel(
            ILogger<ConsentModel> logger, 
            IOpenIddictApplicationManager applicationManager)
        {
            _logger = logger;
            _applicationManager = applicationManager;
        }
        
        [BindProperty]
        public string ReturnUrl { get; set; }
        [BindProperty]
        public string ClientName { get; set; }
        [BindProperty]
        public List<string> Scopes { get; set; } = new List<string> { "基本信息", "邮箱" };
        
        [TempData]
        public string ErrorMessage { get; set; }

        public async Task<IActionResult> OnGet(string returnUrl, string clientid)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                _logger.LogWarning("缺少 ReturnUrl 参数");
                ErrorMessage = "缺少必要参数";
                return Page();
            }

            // 验证clientid参数
            if (string.IsNullOrEmpty(clientid))
            {
                _logger.LogWarning("缺少 ClientId 参数");
                ErrorMessage = "缺少应用标识";
                return Page();
            }

            try
            {
                var application = await _applicationManager.FindByClientIdAsync(clientid);
                if (application == null)
                {
                    _logger.LogWarning("找不到有关调用客户端应用程序的详细信息: {ClientId}", clientid);
                    ErrorMessage = "找不到授权应用";
                    return Page();
                }

                ReturnUrl = returnUrl;
                ClientName = await _applicationManager.GetDisplayNameAsync(application) ?? "未知应用";
                return Page();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取客户端应用信息时发生错误: {ClientId}", clientid);
                ErrorMessage = "系统错误，请重试";
                return Page();
            }
        }

        public async Task<IActionResult> OnPostAsync(string grant)
        {
            if (string.IsNullOrEmpty(grant))
            {
                _logger.LogWarning("未提供授权决定");
                ErrorMessage = "请选择授权决定";
                return Page();
            }
            
            if (string.IsNullOrEmpty(ReturnUrl))
            {
                _logger.LogWarning("缺少 ReturnUrl");
                ErrorMessage = "系统错误，请重试";
                return Page();
            }
            
            try
            {
                // 设置用户的同意状态
                User.SetClaim(Consts.ConsentNaming, grant);
                
                // 重新登录以更新同意状态
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, User);

                // 重定向到授权端点
                return Redirect(ReturnUrl);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "授权处理失败");
                ErrorMessage = "授权处理失败，请重试";
                return Page();
            }
        }
    }
}